package cn.edu.cuit.mockfns.fam.processors;

import java.util.HashMap;
import java.util.Random;

import cn.edu.cuit.mockfns.BusinessLogic;

public class JobPool
    implements Runnable
{

    private static HashMap<Integer, Job> jobs;
    private static Random random;
    private static int maxJobsAmount = 1;
    private static volatile JobPool jobPool;
    private static boolean isStarted;

    private JobPool()
    {
        jobs = new HashMap<Integer, JobPool.Job>();
        random = new Random();
    }

    public static JobPool Instance()
    {
        if( jobPool == null )
        {
            jobPool = new JobPool();
        }

        return jobPool;
    }

    public void run()
    {
        while( isStarted )
            ;
    }

    public static void start()
    {
        isStarted = true;
        new Thread( Instance() ).start();
    }

    public static void stop()
    {
        isStarted = false;
    }

    public void submitJob( BusinessLogic businessLogic )
    {
        // TODO Auto-generated method stub
        int id = random.nextInt( maxJobsAmount );
        if( jobs.get( id ) == null )
        {
            Job job = new Job( id, businessLogic );
            job.run();
            jobs.put( id, job );
        }

    }

    public static Job findCurrentJob( int jobId )
    {
        return jobs.get( jobId );
    }

    /***
     * This method should to be refactored due to that Thread.currentThread().stop() is not safe.
     */
    public static void forceCloseJob( int jobId )
    {
        //TODO
        findCurrentJob( jobId ).stop();
    }

    class Job
        extends Thread
    {
        @SuppressWarnings( "unused" )
        //TODO
        private volatile boolean isStarted;
        @SuppressWarnings( "unused" )
        //TODO
        private final int jobId;
        private Object jobObject;

        public <T extends BusinessLogic> Job(int jobId, T businessLogic)
        {
            this.jobId = jobId;
            jobObject = businessLogic;
            businessLogic.setJobIdentity( jobId );
            isStarted = true;
        }

        private void defaultRun()
        {
            ( (BusinessLogic) jobObject ).defaultLaunch();
        }

        public void run()
        {
            defaultRun();
        }

        public Object getJobObject()
        {
            return jobObject;
        }

        /**
         * Call this method to stop current job thread.
         * */
        public void forceClose()
        {
            //TODO
        }
    }
}
